package com.enjoy.adv.server;

import com.enjoy.adv.vo.MessageType;
import com.enjoy.adv.vo.MyHeader;
import com.enjoy.adv.vo.MyMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Created by HP on 2019/7/19.
 */
public class HeartBeatRespHandler extends ChannelInboundHandlerAdapter {
    private static final Log LOG
            = LogFactory.getLog(HeartBeatRespHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        MyMessage message = (MyMessage) msg;
        if (message.getMyHeader() != null &&
                message.getMyHeader().getType() == MessageType.HEARTBEAT_REQ.getValue()) {
            LOG.info("receive client heart beat message:---->" + message);
            MyMessage heartBeat = buildHeatBeat();
            LOG.info("Send heart beat response message to ---> client");
            ctx.writeAndFlush(heartBeat);
            ReferenceCountUtil.release(msg);
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    private MyMessage buildHeatBeat() {
        MyMessage message = new MyMessage();
        MyHeader myHeader = new MyHeader();
        myHeader.setType(MessageType.HEARTBEAT_RESP.getValue());
        message.setMyHeader(myHeader);
        return message;
    }
}
